package com.sp.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sp.biz.user.bo.DictBO;
import com.sp.biz.user.entity.DictDO;
import com.sp.biz.user.mapper.DictMapper;
import com.sp.biz.user.query.DictParam;
import com.sp.biz.user.service.DictService;
import com.sp.biz.user.vo.DictVO;
import com.sp.common.exception.ServiceException;
import com.sp.common.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-07-16 18:32:42
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, DictDO> implements DictService {

    @Override
    public Page<DictVO> list(DictParam dictParam) {

        Page<DictVO> page = new Page<>(dictParam.getCurrent(),dictParam.getSize());
        return baseMapper.list(page,dictParam);
    }

    @Override
    public void add(DictBO dictBO) {
        if(StringUtils.isEmpty(dictBO.getDictValue())){
            throw new ServiceException("字典类型不能为空");
        }
        Long dictTotal = baseMapper.selectCount(Wrappers.<DictDO>lambdaQuery().eq(DictDO::getDictType,dictBO.getDictValue()));
        if(!Objects.equals(dictTotal,0)){
            throw new ServiceException("字典类型已存在");
        }
        String parentId = StringUtils.isNotEmpty(dictBO.getParentId())?dictBO.getParentId():null;
        String parentIds =null;
        if(parentId!=null){
            DictDO parentDictDO = baseMapper.selectById(parentId);
            if(parentDictDO!=null){
                parentIds = parentDictDO.getParentIds()+","+dictBO.getDictType();
            }
        }
        DictDO dictDO = new DictDO();
        BeanUtil.copyPropertiesIgnoreNull(dictDO,dictDO);
        dictDO.setParentId(parentId);
        dictDO.setParentIds(parentIds);
        baseMapper.insert(dictDO);
    }

    @Override
    public void update(DictBO dictBO) {
        DictDO dictDO = new DictDO();
        BeanUtil.copyPropertiesIgnoreNull(dictDO,dictDO);
        dictDO.setDictType(null);
        dictDO.setParentIds(null);
        dictDO.setParentId(null);
        baseMapper.updateById(dictDO);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }


}
